package com.studyroom.common;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.security.access.AccessDeniedException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BadCredentialsException.class)
    @ResponseBody
    public Result<?> handleBadCredentialsException(BadCredentialsException e) {
        log.error("Invalid credentials: ", e);
        return Result.error(401, "Invalid username or password");
    }

    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    public Result<?> handleAuthenticationException(AuthenticationException e) {
        log.error("Authentication error: ", e);
        return Result.error(401, "认证失败：" + e.getMessage());
    }

    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public Result<?> handleAccessDeniedException(AccessDeniedException e) {
        log.error("Access denied: ", e);
        return Result.error(403, "访问被拒绝：" + e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result<?> handleRuntimeException(RuntimeException e) {
        log.error("Runtime error: ", e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<?> handleException(Exception e) {
        log.error("System error: ", e);
        return Result.error("System error: " + e.getMessage());
    }
} 